//
//  LZMyPersonInfoViewController.m
//  laziz_Consumer
//
//  Created by ZhaoDongBo on 2016/10/27.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMyPersonInfoViewController.h"
#import "LZMyChangeInfoViewController.h"

#import "LZMyPersonInfoTableView.h"

#import "UIViewController+NavigationItemSetting.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZActionSheet.h"

#import "Masonry.h"
#import <MOBFoundation/MOBFoundation.h>

#import "LZUserModel.h"
#import "LZUploadImagePresenter.h"
#import "LZImagePickerManager.h"
#import "LZUserInfoPresenter.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface LZMyPersonInfoViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, LZPictureManagerDelegate>

@property (nonatomic, strong) LZMyPersonInfoTableView * tableView;
@property (nonatomic, weak) LZActionSheet * actionSheet;

@property (nonatomic, strong) NSArray * titleArray;
@property (nonatomic, assign) NSInteger currentSelectType;

@property (strong, nonatomic) LZImagePickerManager *pictureManager;
@property (nonatomic, strong) LZUserInfoPresenter *userInfoPresenter;

@property (nonatomic, strong) LZCurrentUserInfo * currentUserInfo;

@end

@implementation LZMyPersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.umLogPageViewName = @"个人信息页面";
    
    self.title = LZLocalizedString(@"personal_title", @"");
    self.view.backgroundColor = UIColorFromRGB(0xffffff, 1);
    self.userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    self.currentUserInfo = [LZUserModel Instance].userInfo;

    [self setup];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setup {
    
    WS(weakSelf);
    
    [self.view addSubview:self.tableView];
    
    self.tableView.didButtonActionBlock = ^(UIButton * button) {
        
        //取消保存
        [[LZUserModel Instance] logOut];
        if (weakSelf.LogoutActionBlock) {
            weakSelf.LogoutActionBlock();
        }
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    };
    
    self.tableView.didSelectRowBlock = ^(NSIndexPath * indexPath) {
    
        NSInteger section = indexPath.section;
        NSInteger row = indexPath.row;
        LZMyChangeInfoViewController *vc;
    
        if (section == 0) {
            if (row == 0) {
                [weakSelf.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"change_takephoto", @""), LZLocalizedString(@"change_choosephoto", @"")], @[LZLocalizedString(@"cancel", nil)]]];
                [weakSelf.actionSheet ShowView];
            }
            else {
                vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_NICKNAME];
            }
        }
        else {
            if (section == 1) {
                switch (row) {
                    case 0: {
                        if (weakSelf.currentUserInfo.cellphone.length == 0 && weakSelf.currentUserInfo.email.length == 0) {
                            // 如果没绑定手机号也没绑定邮箱，则不能设置密码
                            return ;
                        }
                        else {
                            if (weakSelf.currentUserInfo.password) {
                                vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_CHANGEPASSWORD];
                            } else {
                                vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_SETPASSWORD];
                            }
                        }
                        break;
                    }
                    case 1:
                    {
                        if (weakSelf.currentUserInfo.cellphone.length == 0) {
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_LINKNEW_MOBILE];
                        } else {
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_IDCHECK_MOBILE];
                        }
                        break;
                    }
                    case 2:
                    {
                        if (weakSelf.currentUserInfo.email.length == 0) {
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_SETEMAIL];
                        }
                        else {
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_CHANGEEMAIL];
                        }
                        break;
                    }
                    case 3:
                    {
                        vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_LINKACCOUNT];
                        break;
                    }

                    default:
                        break;
                }
            }
        }
    
        if (vc) {
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
}

- (LZMyChangeInfoViewController *)createChangeInfoWithType:(LZ_MYCHANGEINFO_TYPE)type {
    
    LZMyChangeInfoViewController *vc = [[LZMyChangeInfoViewController alloc] init];
    vc.type = type;
    vc.currentUserInfo = self.currentUserInfo;
    
    WS(weakSelf)
    vc.updataUserInfoBlock = ^(BOOL isChangeUserInfo) {
        
        weakSelf.currentUserInfo = [LZUserModel Instance].userInfo;
        
        weakSelf.tableView.userInfo = weakSelf.currentUserInfo;
    };
    
    return vc;
}

#pragma mark - Setter/Getter

- (LZMyPersonInfoTableView *)tableView {
    
    if (_tableView == nil) {
        _tableView = [[LZMyPersonInfoTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        _tableView.dataArrays = @[@[@"",LZLocalizedString(@"personal_nickname", @"")],
                                  @[LZLocalizedString(@"personal_password", @""),
                                    LZLocalizedString(@"personal_mobliephone", @""),
                                    LZLocalizedString(@"login_email", @""),
                                    LZLocalizedString(@"personal_linkaccount", @"")]];
        
        _tableView.userInfo = self.currentUserInfo;
    }
    
    return _tableView;
}

- (LZActionSheet *)actionSheet {
    if (_actionSheet == nil) {
        LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _actionSheet = sheet;
        [_actionSheet creatHeaderWithTitle:LZLocalizedString(@"change_photo_title", @"") andHeight:41];
        [[UIApplication sharedApplication].keyWindow addSubview:_actionSheet];
        
        WS(weakSelf);
        _actionSheet.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
            if (indexPath.section == 0) {
                [weakSelf LASheetClickedButtonAtIndex:indexPath.row];
            }
        };
    }
    
    return _actionSheet;
}

- (void)LASheetClickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType = 0;
    
    if (buttonIndex == 0) {
        // TakePhotos
        sourceType = UIImagePickerControllerSourceTypeCamera;
    } else if (buttonIndex == 1) {
        // PhotoAlbums
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    
    [self.pictureManager choosePictureWithSourceType:sourceType andPresenterVC:self];
}

#pragma mark - pictureManager的GET方法
- (LZImagePickerManager*)pictureManager {
    if (_pictureManager) {
        return _pictureManager;
    }
    LZImagePickerManager *manager = [[LZImagePickerManager alloc] init];
    manager.allowsEditing = YES;
    manager.delegate = self;
    _pictureManager = manager;
    return _pictureManager;
}

#pragma mark - LZPictureManagerDelegate
- (void)LZPictureManagerFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *aImage = [info objectForKey:UIImagePickerControllerEditedImage];
    if (aImage) {
        [self requestUploadImage:aImage];
    }
}

- (void)requestUploadImage:(UIImage*)aImage {
    WS(weakSelf)
    //上传头像
    [LZUploadImagePresenter uploadImage:aImage
                          andBusinessId:[LZUserModel Instance].userId
                        andBusinessType:@"1"
                          andBusinessNo:@"1"
                             andIsThumb:NO
                                andSize:CGSizeZero
                               andBlock:^(id data, NSError *error) {
                                   if ([[data objectForKey:@"statusCode"] integerValue] == kCodeSuccesss) {
                                       DLog(@"上传头像 %@", data);
                                       
                                       //保存到服务器
                                       NSArray *resultArray = data[@"data"];
                                       if (resultArray.count>0) {
                                           NSDictionary *dic = resultArray[0];
                                           NSString *filePath = dic[@"filePath"];
                                           
                                           [weakSelf.userInfoPresenter userChangeHeadImageFilePath:filePath onSuccess:^(id data) {
                                               DLog(@"保存到服务器 %@", data);
                                               LZCurrentUserInfo *userInfoModel = [LZUserModel Instance].userInfo;
                                               userInfoModel.userPhoto = [data objectForKey:@"data"];
                                               [[LZUserModel Instance] saveUserInfo:userInfoModel];
                                               
                                               weakSelf.currentUserInfo = [LZUserModel Instance].userInfo;
                                               weakSelf.tableView.userInfo = weakSelf.currentUserInfo;

                                           } onFail:^(NSString *fail) {
                                                DLog(@"保存到服务器 error: %@", error);
                                           }];
                                       }
                                   }
                                   else {
                                       DLog(@"上传头像 error: %@", error);
                                   }
                               }];
}

@end
